<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import store from '@/store'
import AddressManager from '@/components/profile/AddressManager.vue'
import NotificationCenter from '@/components/profile/NotificationCenter.vue'

const router = useRouter()

// 用户信息
const userInfo = ref({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: 'https://via.placeholder.com/150',
  gender: '',
  birthday: '',
  address: ''
})

// 订单统计
const orderStats = ref({
  unpaid: 0,
  unshipped: 0,
  shipped: 0,
  completed: 0
})

// 收藏的商品
const favoriteProducts = ref([])

// 最近浏览的商品
const recentlyViewed = ref([])

// 表单是否处于编辑状态
const isEditing = ref(false)

/**
 * 加载用户信息
 * @description 从服务器获取当前登录用户的详细信息
 * @api GET /user/info
 * @params 无需参数，通过token识别用户
 * @response {Object} data - 用户信息对象
 * @response {string} data.username - 用户名
 * @response {string} data.nickname - 用户昵称
 * @response {string} data.email - 用户邮箱
 * @response {string} data.phone - 用户手机号
 * @response {string} data.avatar - 用户头像URL
 * @response {string} data.gender - 用户性别
 * @response {string} data.birthday - 用户生日，格式：YYYY-MM-DD
 * @response {string} data.address - 用户地址
 */
const loadUserInfo = () => {
  // 这里应该调用API获取用户信息
  // API调用后端
  // getUserInfoAPI().then(res => {
  //   userInfo.value = res.data
  // })
  
  // 模拟数据
  userInfo.value = {
    username: 'user123',
    nickname: '球鞋达人',
    email: 'user123@example.com',
    phone: '13800138000',
    avatar: 'https://via.placeholder.com/150',
    gender: '男',
    birthday: '1990-01-01',
    address: '北京市朝阳区'
  }
}

/**
 * 加载订单统计信息
 * @description 从服务器获取当前用户的订单统计数据
 * @api GET /order/stats
 * @params 无需参数，通过token识别用户
 * @response {Object} data - 订单统计信息
 * @response {number} data.unpaid - 待付款订单数量
 * @response {number} data.unshipped - 待发货订单数量
 * @response {number} data.shipped - 待收货订单数量
 * @response {number} data.completed - 已完成订单数量
 */
const loadOrderStats = () => {
  // 这里应该调用API获取订单统计
  // API调用后端
  // getOrderStatsAPI().then(res => {
  //   orderStats.value = res.data
  // })
  
  // 模拟数据
  orderStats.value = {
    unpaid: 2,
    unshipped: 1,
    shipped: 3,
    completed: 10
  }
}

/**
 * 加载用户收藏的商品列表
 * @description 从服务器获取当前用户收藏的商品列表
 * @api GET /user/favorites
 * @params 无需参数，通过token识别用户
 * @response {Array} data - 收藏商品列表
 * @response {number} data[].id - 商品ID
 * @response {string} data[].name - 商品名称
 * @response {string} data[].brand - 商品品牌
 * @response {number} data[].price - 商品价格
 * @response {string} data[].image - 商品图片URL
 */
const loadFavoriteProducts = () => {
  // 这里应该调用API获取收藏商品列表
  // API调用后端
  // getFavoriteProductsAPI().then(res => {
  //   favoriteProducts.value = res.data
  // })
  
  // 模拟数据
  favoriteProducts.value = [
    {
      id: 1,
      name: 'Air Jordan 1',
      brand: 'Nike',
      price: 1299,
      image: 'https://via.placeholder.com/300x300?text=AJ1'
    },
    {
      id: 2,
      name: 'Ultra Boost',
      brand: 'Adidas',
      price: 1199,
      image: 'https://via.placeholder.com/300x300?text=UltraBoost'
    }
  ]
}

/**
 * 加载用户最近浏览的商品列表
 * @description 从服务器获取当前用户最近浏览的商品列表
 * @api GET /user/recently-viewed
 * @params 无需参数，通过token识别用户
 * @response {Array} data - 最近浏览商品列表
 * @response {number} data[].id - 商品ID
 * @response {string} data[].name - 商品名称
 * @response {string} data[].brand - 商品品牌
 * @response {number} data[].price - 商品价格
 * @response {string} data[].image - 商品图片URL
 */
const loadRecentlyViewed = () => {
  // 这里应该调用API获取最近浏览商品列表
  // API调用后端
  // getRecentlyViewedAPI().then(res => {
  //   recentlyViewed.value = res.data
  // })
  
  // 模拟数据
  recentlyViewed.value = [
    {
      id: 3,
      name: 'Dunk Low',
      brand: 'Nike',
      price: 899,
      image: 'https://via.placeholder.com/300x300?text=DunkLow'
    },
    {
      id: 4,
      name: 'New Balance 550',
      brand: 'New Balance',
      price: 899,
      image: 'https://via.placeholder.com/300x300?text=NB550'
    }
  ]
}

/**
 * 保存用户信息
 * @description 将用户修改后的个人信息保存到服务器
 * @api POST /user/update
 * @params {Object} userInfo - 用户信息对象
 * @params {string} userInfo.nickname - 用户昵称
 * @params {string} userInfo.email - 用户邮箱
 * @params {string} userInfo.phone - 用户手机号
 * @params {string} userInfo.gender - 用户性别
 * @params {string} userInfo.birthday - 用户生日，格式：YYYY-MM-DD
 * @params {string} userInfo.address - 用户地址
 * @response {number} code - 状态码，200表示成功
 * @response {string} message - 操作结果信息
 */
const saveUserInfo = () => {
  // 这里应该调用API保存用户信息
  // API调用后端
  // updateUserInfoAPI(userInfo.value).then(() => {
  //   ElMessage.success('保存成功')
  //   isEditing.value = false
  // })
  
  // 模拟保存成功
  setTimeout(() => {
    ElMessage.success('保存成功')
    isEditing.value = false
  }, 500)
}

// 退出登录
const logout = () => {
  store.clearUserInfo()
  router.push('/login')
}

onMounted(() => {
  loadUserInfo()
  loadOrderStats()
  loadFavoriteProducts()
  loadRecentlyViewed()
})
</script>

<template>
  <div class="user-profile">
    <div class="container">
      <!-- 用户基本信息卡片 -->
      <el-card class="info-card">
        <div class="user-header">
          <el-avatar :size="100" :src="userInfo.avatar" />
          <div class="user-basic-info">
            <h2>{{ userInfo.nickname }}</h2>
            <p>{{ userInfo.username }}</p>
          </div>
          <div class="back-button" @click="router.push('/user')">
            <el-icon :size="24"><ArrowLeft /></el-icon>
            <span>返回</span>
          </div>
          <div class="header-actions">
            <el-button v-if="!isEditing" type="primary" @click="isEditing = true">编辑资料</el-button>
            <template v-else>
              <el-button @click="isEditing = false">取消</el-button>
              <el-button type="primary" @click="saveUserInfo">保存</el-button>
            </template>
            <el-button type="danger" @click="logout">退出登录</el-button>
          </div>
        </div>

        <el-form :model="userInfo" label-width="100px" :disabled="!isEditing">
          <el-form-item label="昵称">
            <el-input v-model="userInfo.nickname" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="userInfo.phone" />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="userInfo.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker v-model="userInfo.birthday" type="date" placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="userInfo.address" type="textarea" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 订单统计卡片 -->
      <el-card class="stats-card">
        <template #header>
          <div class="card-header">
            <h3>我的订单</h3>
            <el-button text @click="router.push('/orders')">查看全部</el-button>
          </div>
        </template>
        <div class="order-stats">
          <div class="stat-item">
            <h4>{{ orderStats.unpaid }}</h4>
            <p>待付款</p>
          </div>
          <div class="stat-item">
            <h4>{{ orderStats.unshipped }}</h4>
            <p>待发货</p>
          </div>
          <div class="stat-item">
            <h4>{{ orderStats.shipped }}</h4>
            <p>待收货</p>
          </div>
          <div class="stat-item">
            <h4>{{ orderStats.completed }}</h4>
            <p>已完成</p>
          </div>
        </div>
      </el-card>

      <!-- 收藏商品卡片 -->
      <el-card class="favorites-card">
        <template #header>
          <div class="card-header">
            <h3>我的收藏</h3>
            <el-button text @click="router.push('/favorites')">查看全部</el-button>
          </div>
        </template>
        <div class="product-grid">
          <el-card v-for="product in favoriteProducts" :key="product.id" class="product-card">
            <img :src="product.image" :alt="product.name" class="product-image">
            <h4>{{ product.name }}</h4>
            <p class="brand">{{ product.brand }}</p>
            <p class="price">¥{{ product.price }}</p>
          </el-card>
        </div>
      </el-card>

      <!-- 最近浏览卡片 -->
      <el-card class="recently-viewed-card">
        <template #header>
          <div class="card-header">
            <h3>最近浏览</h3>
            <el-button text @click="router.push('/recently-viewed')">查看全部</el-button>
          </div>
        </template>
        <div class="product-grid">
          <el-card v-for="product in recentlyViewed" :key="product.id" class="product-card">
            <img :src="product.image" :alt="product.name" class="product-image">
            <h4>{{ product.name }}</h4>
            <p class="brand">{{ product.brand }}</p>
            <p class="price">¥{{ product.price }}</p>
          </el-card>
        </div>
      </el-card>

      <!-- 地址管理 -->
      <AddressManager />

      <!-- 消息中心 -->
      <NotificationCenter />
    </div>
  </div>
</template>

<style scoped>
.user-profile {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
  position: relative;
}

.back-button {
  position: absolute;
  top: 24px;
  left: 24px;
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.back-button:hover {
  color: #409EFF;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 24px;
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.user-basic-info {
  margin-left: 24px;
  flex: 1;
}

.user-basic-info h2 {
  margin: 0 0 8px;
  font-size: 24px;
}

.user-basic-info p {
  margin: 0;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.order-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
  padding: 20px 0;
}

.stat-item h4 {
  margin: 0 0 8px;
  font-size: 24px;
  color: #409EFF;
}

.stat-item p {
  margin: 0;
  color: #606266;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px;
}

.product-card {
  border: none;
  transition: transform 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.product-card h4 {
  margin: 12px 0 8px;
  font-size: 16px;
}

.brand {
  color: #909399;
  margin: 0 0 8px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}
</style>